<template>
	<div class="grid grid-flow-col gap-5 text-center auto-cols-max">
		<div class="flex flex-col">
			<span class="countdown font-mono text-6xl">
				<span :style="`--value: ${timeSet.hour}`"></span>
			</span>
			hours
		</div>
		<div class="flex flex-col">
			<span class="countdown font-mono text-6xl">
				<span :style="`--value: ${timeSet.minute}`"></span>
			</span>
			min
		</div>
		<div class="flex flex-col">
			<span class="countdown font-mono text-6xl">
				<span :style="`--value: ${timeSet.second}`"></span>
			</span>
			sec
		</div>
	</div>
</template>

<script lang="ts">
  type Callback = (time: number) => void
  export type TimeRecordType = {
    update: (callback?: Callback) => void
    reset: () => void
  }
</script>
<script setup lang="ts">
  import { reactive, onMounted } from 'vue'
  import { getStatus, STATUS_REST, STATUS_WORK, setTime, getTime, getTimeRecord } from '../../storage'
  import { createCountDown } from 'iius'

  const timeSet = reactive({ hour: 0, minute: 0, second: 0 })
  let timer: number | null = null

  const update = (callback?: Callback) => {
    // 判断当前状态
    // 如果是上班状态，先清除定时器，然后再重新开启定时器
    // 如果是下班状态，直接清除计时器
    const status = getStatus()

    timer && clearInterval(timer)
    // 下班状态
    if (status === STATUS_REST) {
      return timer = null
    }

    timer = setInterval(() => {
      const old = getTime()
      const now = old + 1000
      const { hour, minute, second } = createCountDown(now)

      timeSet.hour = +hour
      timeSet.minute = +minute
      timeSet.second = +second
      setTime(now)
      callback && callback(now)
    }, 1000)
  }

  const reset = () => {
    timer && clearInterval(timer)
    timeSet.hour = 0
    timeSet.minute = 0
    timeSet.second = 0
  }

  const initTime = () => {
    const status = getStatus()
    if (status === STATUS_WORK) {
      // 获取最新的记录，计算时间差
      const latestRecord = getTimeRecord().pop()
      const timeDiff = Date.now() - latestRecord?.timeStamp!
      setTime(timeDiff)
    }
    const time = getTime()
    const { hour, minute, second } = createCountDown(time)
    timeSet.hour = +hour
    timeSet.minute = +minute
    timeSet.second = +second
    update()
  }

  onMounted(() => {
    initTime()
  })

  defineExpose<TimeRecordType>({
    update,
    reset
  })
</script>

<style scoped lang="scss"></style>
